package com.zyh.utils;
import java.sql.*;
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantLock;

public class JdbcUtils {

    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/game";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final int INIT_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final LinkedList<Connection> CONNECTION_POOL = new LinkedList<>();
    private static final ReentrantLock LOCK = new ReentrantLock();

    static {
        try {
            Class.forName(DRIVER);
            for (int i = 0; i < INIT_POOL_SIZE; i++) {
                CONNECTION_POOL.add(createConnection());
            }
        } catch (Exception e) {
            throw new RuntimeException("数据库连接池初始化失败", e);
        }
    }

    private static Connection createConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static Connection getConnection() throws SQLException {
        LOCK.lock();
        try {
            if (CONNECTION_POOL.isEmpty()) {
                if (CONNECTION_POOL.size() < MAX_POOL_SIZE) {
                    CONNECTION_POOL.add(createConnection());
                } else {
                    throw new SQLException("连接池已满");
                }
            }
            return CONNECTION_POOL.removeFirst();
        } finally {
            LOCK.unlock();
        }
    }

    public static void releaseConnection(Connection conn) {
        LOCK.lock();
        try {
            if (conn != null) {
                CONNECTION_POOL.addLast(conn);
            }
        } finally {
            LOCK.unlock();
        }
    }

    public void closeAllConnections() {
        LOCK.lock();
        try {
            for (Connection conn : CONNECTION_POOL) {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            CONNECTION_POOL.clear();
        } catch (Exception e) {
            throw new RuntimeException("关闭连接失败", e);
        } finally {
            LOCK.unlock();
        }
    }
}
